package com.ego.product.web;

import com.alibaba.fastjson.TypeReference;
import com.ego.common.constant.SystemConstant;
import com.ego.common.to.member.MemberGroupTo;
import com.ego.common.util.Result;
import com.ego.product.feign.CouponFeign;
import com.ego.product.interceptor.IndexInterceptor;
import com.ego.product.po.Category;
import com.ego.product.service.CartService;
import com.ego.product.service.CategoryService;
import com.ego.product.to.coupon.SeckillSkuInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * @program: ego
 * @description: 首页
 * @author: KamTang
 * @create: 2022-11-30 11:01
 **/
@Controller
@Slf4j
public class IndexController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private CouponFeign couponFeign;
    @Autowired
    private CartService cartService;

    @GetMapping({"/", "index", "/index.html"})
    public String indexPage(Model model, HttpSession session) throws ExecutionException, InterruptedException {
        // 首页三级分类
        List<Category> categories = categoryService.cascade();
        model.addAttribute("categories", categories);
        MemberGroupTo memberGroup = IndexInterceptor.threadLocal.get();
        Integer numCount = cartService.get(memberGroup).getNumCount();
        session.setAttribute("goodNumInCart", numCount);
        try {
            Result currentSeckillSkuResp = couponFeign.getCurrentSeckillSku();
            if (currentSeckillSkuResp.getCode() == SystemConstant.Status.SUCCESS.getCode()) {
                List<SeckillSkuInfoTo> skuInfoTos = currentSeckillSkuResp.getData("skuInfoTo", new TypeReference<List<SeckillSkuInfoTo>>() {
                });
                model.addAttribute("seckillSkus", skuInfoTos);
            }
        } catch (Exception e) {
            log.info("优惠服务器出错......");
        }

        return "index";
    }

}
